package com.mtnz.njk.Service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.github.pagehelper.PageHelper;
import com.mtnz.njk.Mapper.*;
import com.mtnz.njk.Util.ExcelUtil;
import com.mtnz.njk.Util.MapDistance;
import com.mtnz.njk.Util.NewDateUtil;
import com.mtnz.njk.entity.*;
import com.mtnz.njk.model.*;
import com.mtnz.njk.result.PageInfo;
import com.mtnz.njk.result.ResponseMessage;
import com.mtnz.njk.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 研究院帖子业务层
 * @Author: ZPX
 * @CreateDate: 2019/8/13 9:12
 * @Version: 1.0
 */
@Service
public class ResearchManagerService {

    @Autowired
    ResearchManageMapper researchManageMapper; //研究院

    @Autowired
    NewsMapper newsMapper;//消息

    @Autowired
    ProductMapper productMapper;//商品

    @Autowired
    NjkUserMapper njkUserMapper;//用户

    @Autowired
    NjkUserInfoMapper njkUserInfoMapper;//用户扩展信息

    @Autowired
    ResearchImgManageMapper researchImgManageMapper;//帖子图

    @Autowired
    CommentResearchManageMapper commentResearchManageMapper;

    @Autowired
    PraiseCommentResearchManageMapper praiseCommentResearchMapper;

    @Autowired
    CommentResearchImgManageMapper commentResearchImgManageMapper;

    @Autowired
    CalendarMapper calendarMapper;

    @Autowired
    AskManageMapper askManageMapper;

    @Autowired
    CountCommunityManageMapper countCommunityManageMapper;

    @Autowired
    IntegralManagerMapper integralManagerMapper;

    @Autowired
    ResearchBannerManageMapper researchBannerManageMapper;

    /**
     * 转移研究院帖子
     *
     * @param productId  产品ID
     * @param researchId 研究院ID
     * @return
     */
    @Transactional
    public ResponseResult shiftResearch(String productId, String researchId) throws Exception {
        String[] split = researchId.split(",");
        for (String s : split) {
            //修改帖子对应的研究社
            researchManageMapper.updateResearch(productId, s);

            //获取研究社数据
            ResearchEntity researchEntity = researchManageMapper.selectByPrimaryKey(s);
            //获取商品信息
            ProductEntity productEntity = productMapper.selectByPrimaryKey(productId);
            //获取用户表
            NjkUserEntity njkUserEntity = njkUserMapper.selectByPrimaryKey(researchEntity.getUserId());
            //获取用户扩展信心
            Example example = new Example(NjkUserInfoEntity.class);
            example.createCriteria().andEqualTo("userId", researchEntity.getUserId());
            List<NjkUserInfoEntity> njkUserInfoEntities = njkUserInfoMapper.selectByExample(example);
            NjkUserInfoEntity njkUserInfoEntity = njkUserInfoEntities.get(0);
            //保存消息
            NewsEntity newsEntity = new NewsEntity();
            newsEntity.setNewsId(IdUtil.simpleUUID());
            newsEntity.setId(researchEntity.getResearchId().toString());
            newsEntity.setMessage(researchEntity.getContent());
            newsEntity.setName(njkUserEntity.getNickName());
            newsEntity.setImg(njkUserInfoEntity.getImg());
            newsEntity.setCreateDate(DateUtil.now());
            newsEntity.setUserId(researchEntity.getUserId());
            newsEntity.setSubject(researchEntity.getSubject());
            newsEntity.setStatus("8");
            newsEntity.setUserId1(researchEntity.getUserId());
            newsEntity.setUserId1(researchEntity.getUserId());
            newsEntity.setUrl("");
            newsEntity.setAlert(researchEntity.getSubject() + "已被转移至" + productEntity.getProductName() + "产品讨论区");
            newsMapper.insert(newsEntity);
        }
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 删除研究院帖子
     *
     * @param researchId
     * @return
     */
    @Transactional
    public ResponseResult deleteResearch(String researchId) {
        //获取研究社数据
        ResearchEntity researchEntity = researchManageMapper.selectByPrimaryKey(researchId);
        //获取用户表
        NjkUserEntity njkUserEntity = njkUserMapper.selectByPrimaryKey(researchEntity.getUserId());
        //获取用户扩展信心
        Example example = new Example(NjkUserInfoEntity.class);
        example.createCriteria().andEqualTo("userId", researchEntity.getUserId());
        List<NjkUserInfoEntity> njkUserInfoEntities = njkUserInfoMapper.selectByExample(example);
        NjkUserInfoEntity njkUserInfoEntity = njkUserInfoEntities.get(0);
        //保存消息
        NewsEntity newsEntity = new NewsEntity();
        newsEntity.setNewsId(IdUtil.simpleUUID());
        newsEntity.setId(researchEntity.getResearchId().toString());
        newsEntity.setMessage(researchEntity.getContent());
        newsEntity.setName(njkUserEntity.getNickName());
        newsEntity.setImg(njkUserInfoEntity.getImg());
        newsEntity.setCreateDate(DateUtil.now());
        newsEntity.setUserId(researchEntity.getUserId());
        newsEntity.setSubject(researchEntity.getSubject());
        newsEntity.setStatus("8");
        newsEntity.setUserId1(researchEntity.getUserId());
        newsEntity.setUrl("");
        newsEntity.setAlert("您的" + researchEntity.getSubject() + "帖子因不合社区规定，已被后台删除");
        newsMapper.insert(newsEntity);
        researchManageMapper.deleteByPrimaryKey(researchId);
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 编辑研究院帖子
     *
     * @param researchId 帖子ID
     * @param subject    标题
     * @param topStatus  是否置顶
     * @param coverImg   封面图
     * @param shareImg   分享图
     * @param content    内容
     * @return
     */
    @Transactional
    public ResponseResult updateResearch(String productId, String cpmImg, String activeImg, String activeStatus, String researchId, String subject, String topStatus, String coverImg, String shareImg, String content, String activeEndTime) throws Exception {
        //获取帖子数据
        ResearchEntity researchEntity = researchManageMapper.selectByPrimaryKey(researchId);
        //更新图片
        if (coverImg != null) {
            researchImgManageMapper.updateResearchImgCoverImg(researchId, coverImg);
        }
        if (shareImg != null) {
            researchImgManageMapper.updateResearchImgShareImg(researchId, shareImg);
        }

        if (activeStatus != null && activeStatus != "") {
            researchEntity.setActiveStatus(activeStatus);
        }
        if ("1".equals(activeStatus)) {
            //把该研究院的活动状态该为0
            Example example = new Example(ResearchEntity.class);
            example.createCriteria().andEqualTo("productId", productId);
            List<ResearchEntity> researchEntities = researchManageMapper.selectByExample(example);
            for (ResearchEntity entity : researchEntities) {
                entity.setActiveStatus("0");
                researchManageMapper.updateByPrimaryKeySelective(entity);
            }
            researchEntity.setActiveStatus(activeStatus);
        }
        if (activeImg != null && activeImg != "") {
            researchEntity.setActiveImg(activeImg);
        }
        if (cpmImg != null && cpmImg != "") {
            researchEntity.setCpmImg(cpmImg);
        }
        if (topStatus != null && topStatus != "") {
            researchEntity.setTopStatus(topStatus);
        }
        if (subject != null && subject != "") {
            researchEntity.setSubject(subject);
        }
        if (content != null && content != "") {
            researchEntity.setContent(content);
        }
        if (activeEndTime != null && !"".equals(activeEndTime)) {
            researchEntity.setActiveEndTime(DateUtil.parse(activeEndTime,"yyyy-MM-dd"));
        }
        researchManageMapper.updateByPrimaryKey(researchEntity);
        return new ResponseResult(ResponseMessage.OK);
    }


    /**
     * 添加帖子
     *
     * @param researchModel
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult addResearch(ResearchManageModel researchModel) throws Exception {

        //获取用户信息
        NjkUserEntity njkUserEntity = njkUserMapper.selectByPrimaryKey(researchModel.getUserId());
        ResearchEntity researchEntity = new ResearchEntity();
        researchEntity.setSubject(researchModel.getSubject());
        researchEntity.setProductId(researchModel.getProductId());
        researchEntity.setUserId(researchModel.getUserId());
        researchEntity.setName(njkUserEntity.getNickName());
        researchEntity.setRecoverDate(DateUtil.now());
        researchEntity.setViews(0);
        researchEntity.setRecover(0);
        researchEntity.setAppraisal("0");
        researchEntity.setCream(0);
        researchEntity.setDateStatus("0");
        researchEntity.setPraiseStatus("0");
        researchEntity.setPublish("1");
        researchEntity.setTopStatus("0");

        //把该研究院的活动状态该为0
        Example example = new Example(ResearchEntity.class);
        example.createCriteria().andEqualTo("productId", researchModel.getProductId());
        List<ResearchEntity> researchEntities = researchManageMapper.selectByExample(example);
        for (ResearchEntity entity : researchEntities) {
            entity.setActiveStatus("0");
            researchManageMapper.updateByPrimaryKeySelective(entity);
        }

        //判断是否为活动0否1是
        if (researchModel.getActiveStatus() != null && !"".equals(researchModel.getActiveStatus())) {
            if ("1".equals(researchModel.getActiveStatus())) {
                researchEntity.setActiveStatus("1");
                researchEntity.setOperatingStatus("1");
                researchEntity.setActiveEndTime(researchModel.getActiveEndTime());
            } else {
                researchEntity.setActiveStatus("0");
                researchEntity.setOperatingStatus("0");
            }
        }
//        researchEntity.setActiveStatus("0");
        researchEntity.setShareViews(0);
        researchEntity.setClickViews(0);
        //保存活动弹窗图
        if (researchModel.getCpmImg() != null && !"".equals(researchModel.getCpmImg())) {
            researchEntity.setCpmImg(researchModel.getCpmImg());
        }
        //保存活动图
        if (researchModel.getActiveImg() != null && !"".equals(researchModel.getActiveImg())) {
            researchEntity.setActiveImg(researchModel.getActiveImg());
        }
        //保存图片内容
        String replace = researchModel.getContent().replace("!==!", "<br/>");
        String replace1 = replace.replace("\n", "<br/>");

        if (researchModel.getImg() != null && researchModel.getImg() != "") {
            String[] split = researchModel.getImg().split(",");
            for (String s : split) {
                replace1 += "<br/><img src=" + s + "><br/>";
            }
        }
        researchEntity.setContent("<style>img{max-width:100%;}</style><p>" + replace1 + "</p>");
        researchEntity.setCreateTime(researchEntity.getRecoverDate());
        //获取坐标
        String address = "";
        if (researchModel.getLat() != null && researchModel.getLat().length() > 4 && researchModel.getLng() != null && researchModel.getLng().length() > 4) {
            address = MapDistance.getCoordinate3(researchModel.getLng(), researchModel.getLat());
        } else {
            address = "农极客";
        }
        researchEntity.setAddress(address);
        researchManageMapper.insert(researchEntity);

        //保存到图片表
        ResearchImgEntity researchImgEntity = new ResearchImgEntity();
        if (researchModel.getImg() != null && researchModel.getImg() != "") {
            String[] imgs = researchModel.getImg().split(",");
            List<String> strings = Arrays.asList(imgs);
            for (int i = 0; i < strings.size(); i++) {
                researchImgEntity.setResearchId(researchEntity.getResearchId());
                researchImgEntity.setImg(strings.get(i));
                researchImgEntity.setOrdeBy(String.valueOf(i + 1));
                researchImgEntity.setCreateDate(DateUtil.now());
                researchImgManageMapper.insert(researchImgEntity);
            }
        }

        //保存分享图
        if (researchModel.getShareImg() != null) {
            researchImgEntity.setResearchId(researchEntity.getResearchId());
            researchImgEntity.setCreateDate(DateUtil.now());
            researchImgEntity.setOrdeBy(String.valueOf(1));
            researchImgEntity.setShareImg(researchModel.getShareImg());
            if (researchModel.getCoverImg() != null) {
                researchImgEntity.setResearchId(researchEntity.getResearchId());
                researchImgEntity.setCreateDate(DateUtil.now());
                researchImgEntity.setOrdeBy(String.valueOf(1));
                researchImgEntity.setCoverImg(researchModel.getCoverImg());
            }
            researchImgManageMapper.insert(researchImgEntity);
        }
        //保存封面图
        if (researchModel.getCoverImg() != null) {
            researchImgEntity.setResearchId(researchEntity.getResearchId());
            researchImgEntity.setCreateDate(DateUtil.now());
            researchImgEntity.setOrdeBy(String.valueOf(1));
            researchImgEntity.setCoverImg(researchModel.getCoverImg());
            if (researchModel.getShareImg() != null) {
                researchImgEntity.setResearchId(researchEntity.getResearchId());
                researchImgEntity.setCreateDate(DateUtil.now());
                researchImgEntity.setOrdeBy(String.valueOf(1));
                researchImgEntity.setShareImg(researchModel.getShareImg());
            }
            researchImgManageMapper.insert(researchImgEntity);
        }

        if ("1".equals(researchModel.getActiveStatus())) {
            List<NjkUserEntity> njkUserEntities = njkUserMapper.selectAll();

        }
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 是否为精
     *
     * @param researchId
     * @param cream
     * @return
     */
    @Transactional
    public ResponseResult updateCream(String researchId, String cream) throws Exception {
        if ("1".equals(cream) && cream != null) {
            researchManageMapper.updateCream(cream, researchId);
        } else {
            researchManageMapper.updateCream(cream, researchId);
        }
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 评论列表
     *
     * @param researchId
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public ResponseResult showReply(Integer researchId, String userId, Integer pageNum, Integer pageSize) throws Exception {
        //分页
        PageHelper.startPage(pageNum, pageSize);
        Example example10 = new Example(CommentResearchManageModel.class);
        example10.createCriteria().andEqualTo("researchId", researchId);
        List<CommentResearchManageModel> commentResearchManageModels = commentResearchManageMapper.selectByExample(example10);

        for (CommentResearchManageModel commentResearchManageModel : commentResearchManageModels) {
            //获取评论人姓名
            Example example1 = new Example(NjkUserEntity.class);
            example1.createCriteria().andEqualTo("userId", commentResearchManageModel.getUserId());
            List<NjkUserEntity> njkUserEntities = njkUserMapper.selectByExample(example1);
            for (NjkUserEntity njkUserEntity : njkUserEntities) {
                String name = njkUserEntity.getNickName();
                commentResearchManageModel.setNickName(name);
            }

            //查询是否点过赞
            if (userId != null && !userId.equals("")) {
                PraiseCommentResearchEntity praiseCommentResearchEntity = praiseCommentResearchMapper.showPraiseCommentStatus(commentResearchManageModel.getCommentResearchId().toString(), userId);
                if (praiseCommentResearchEntity != null) {
                    commentResearchManageModel.setZan("1");
                } else {
                    commentResearchManageModel.setZan("0");
                }
            }

            //获取回复人姓名
            Example example2 = new Example(NjkUserEntity.class);
            example2.createCriteria().andEqualTo("userId", commentResearchManageModel.getReplyId());
            List<NjkUserEntity> njkUserEntities1 = njkUserMapper.selectByExample(example2);
            for (NjkUserEntity njkUserEntity : njkUserEntities1) {
                String name = njkUserEntity.getNickName();
                commentResearchManageModel.setPName(name);
            }

        }

        PageInfo pageInfo = new PageInfo<>(commentResearchManageModels);
        return new ResponseResult(ResponseMessage.OK, pageInfo);
    }

    /**
     * 删除评论
     *
     * @param commentResearchId
     * @return
     */
    @Transactional
    public ResponseResult delComment(String commentResearchId) {
        String[] split = commentResearchId.split(",");
        for (String s : split) {
            commentResearchManageMapper.deleteByPrimaryKey(s);
        }
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 添加帖子评论
     *
     * @return
     */
    @Transactional
    public ResponseResult addCommentResearch(String researchId, String userId, String message, String img) {

        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("researchId", researchId);
        paramMap.put("userId", userId);
        paramMap.put("message", message);
        paramMap.put("img", img);
        String s = HttpUtil.toParams(paramMap);
        String result = HttpUtil.post("http://localhost:9998/community/saveCommentResearch", s);

        return new ResponseResult(ResponseMessage.OK, result);
    }

    /**
     * 回复评论
     *
     * @param userId
     * @param researchId
     * @param message
     * @param commentResearchId
     * @return
     */
    @Transactional
    public ResponseResult commentResearchReply(String userId, String researchId, String message, String commentResearchId) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("researchId", researchId);
        paramMap.put("userId", userId);
        paramMap.put("message", message);
        paramMap.put("commentResearchId", commentResearchId);
        String s = HttpUtil.toParams(paramMap);
        String result = HttpUtil.post("http://localhost:9998/community/commentResearchReply", s);

        return new ResponseResult(ResponseMessage.OK, result);
    }

    /**
     * 回复评论回复
     *
     * @param researchId 研究院
     * @param userId     用户
     * @param message    内容
     * @param pid        上一条回复的ID
     * @return
     */
    @Transactional
    public ResponseResult commentResearchReplys(String userId, String researchId, String message, String replyId, String pid) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("researchId", researchId);
        paramMap.put("userId", userId);
        paramMap.put("message", message);
        paramMap.put("replyId", replyId);
        paramMap.put("pid", pid);
        String s = HttpUtil.toParams(paramMap);
        String result = HttpUtil.post("http://localhost:9998/community/commentResearchReplyS", s);

        return new ResponseResult(ResponseMessage.OK, result);
    }


    /**
     * 研究院统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param status    0月1年
     * @return
     */
    public ResponseResult researchStatistics(String startTime, String endTime, String status) throws Exception {

        //封装结果
        Map map = new HashMap();
        //判断时间不为空
        if (startTime != null && endTime != null && !"".equals(startTime) && !"".equals(endTime)) {
            //获取时间内的数据
            List<ResearchStatisticsModel> recoverDate = researchManageMapper.findRecoverDate(startTime, endTime);

            //日历
            List<CalendarEntity> calendarEntities = calendarMapper.selDateAll(startTime, endTime);
            for (CalendarEntity calendarEntity : calendarEntities) {
                //遍历researchStatistics
                for (ResearchStatisticsModel researchStatisticsModel : recoverDate) {
                    //获取时间
                    String recoverDate1 = researchStatisticsModel.getRecoverDate();
                    Date date = DateUtil.parse(recoverDate1);
                    String format1 = DateUtil.format(date, "yyyy-MM-dd");
                    //对比日历的时间
                    if (format1.equals(calendarEntity.getDateList())) {
                        //得到分享数
                        String sumShareViews = researchStatisticsModel.getSumShareViews();
                        if (sumShareViews != null && !"".equals(sumShareViews)) {
                            Integer views = Integer.parseInt(sumShareViews);
                            calendarEntity.setShareViews(views);
                        }
                        //得到发帖数
                        String countResearch = researchStatisticsModel.getCountResearch();
                        if (countResearch != null && !"".equals(countResearch)) {
                            Integer i = Integer.parseInt(countResearch);
                            calendarEntity.setResearchViews(i);
                        }
                    }
                }
                map.put("Statistics", calendarEntities);
            }
        }
        //status是O查询月数据
        if ("0".equals(status)) {
            //获取当前时间
            //当前时间字符串，格式：yyyy-MM-dd HH:mm:ss
            String now = DateUtil.now();

            //获取当前时间的前一个月
            Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
            ca.setTime(new Date()); // 设置时间为当前时间
            ca.add(Calendar.MONTH, -1);// 月份减1
            Date resultDate = ca.getTime(); // 结果
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(resultDate);
            Map map1 = researchManageMapper.findRecoverDateMonth(format, now);
            //日历
            List<CalendarEntity> calendarEntities = calendarMapper.selAll(format, now);

            for (CalendarEntity calendarEntity : calendarEntities) {
                //获取时间
                Object recover_date = map1.get("recover_date");
                String s = recover_date.toString();
                Date date = DateUtil.parse(s);
                String format1 = DateUtil.format(date, "yyyy-MM-dd");
                if (format1.equals(calendarEntity.getDateList())) {
                    //获取分享数
                    Object o = map1.get("sum(share_views)");
                    String s1 = o.toString();
                    if (s1 != null && !"".equals(s1)) {
                        Integer views = Integer.parseInt(s1);
                        calendarEntity.setShareViews(views);
                    }
                }
            }

            map.put("Statistics", calendarEntities);
        }

        //status是1查询年数据
        if ("1".equals(status)) {
            //获取当前时间
            //当前时间字符串，格式：yyyy-MM-dd HH:mm:ss
            String now = DateUtil.now();
            //获取当前时间的前一年
            Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
            ca.setTime(new Date()); // 设置时间为当前时间
            ca.add(Calendar.YEAR, -1); // 年份减1
            Date resultDate = ca.getTime(); // 结果
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(resultDate);
            //获取这一年时间段的所有帖子，根据帖子创建时间查询每月的发帖数和分享数
            List<ResearchStatisticsModel> recoverDate = researchManageMapper.findRecoverDateYear(format, now);

            //日历
            List<CalendarEntity> calendarEntities = calendarMapper.selAllYear(format, now);
            for (CalendarEntity calendarEntity : calendarEntities)
                for (ResearchStatisticsModel researchStatisticsModel : recoverDate) {
                    //获取时间进行对比
                    String recoverDate1 = researchStatisticsModel.getRecoverDate();
                    Date date = DateUtil.parse(recoverDate1);
                    String format1 = DateUtil.format(date, "yyyy-MM");
                    if (format1 == null && "".equals(format1)) {
                        calendarEntity.setShareViews(0);
                        calendarEntity.setResearchViews(0);
                    }
                    String dateList = calendarEntity.getDateList();
                    Date date1 = DateUtil.parse(dateList);
                    String format2 = DateUtil.format(date1, "yyyy-MM");
                    if (format1.equals(format2)) {
                        String sumShareViews = researchStatisticsModel.getSumShareViews();
                        if (sumShareViews != null && !"".equals(sumShareViews)) {
                            Integer views = Integer.parseInt(sumShareViews);
                            calendarEntity.setShareViews(views);
                        }
                        String countResearch = researchStatisticsModel.getCountResearch();
                        if (countResearch != null && !"".equals(countResearch)) {
                            calendarEntity.setResearchViews(Integer.parseInt(countResearch));
                        }
                    }
                    calendarEntity.setYear(format2);
                }
            map.put("Statistics", calendarEntities);
        }

        return new ResponseResult(ResponseMessage.OK, map);
    }

    /**
     * 分享运营导出excel
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    public ResponseResult exportExcel(HttpServletResponse response, String startTime, String endTime) throws Exception {
        List<String> strs = NewDateUtil.getDays(startTime, endTime);
        //excel模型
        List<String[]> excelModels = new ArrayList<>();
        List<String[]> string = new ArrayList<>();
        for (int i = 0; i < strs.size(); i++) {
            String time = strs.get(i);
            List<ExcelModel> excel = researchManageMapper.findExcel(time);
            if (time != null) {
                String[] str1 = new String[0];
                for (ExcelModel excelModel : excel) {
                    str1 = new String[]{"总计", ".", ".", ".", ".", excelModel.getCountResearch() + ".", excelModel.getCountResearchShareNum() + ".", excelModel.getCountAsk() + ".", excelModel.getCountAskShareNum() + ".", excelModel.getProductShareViews() + ".", excelModel.getIntegralShopShareViews() + "."};
                }
                excelModels.add(str1);
            }
            for (ExcelModel excelModel : excel) {
                String[] str = new String[11];
                str[0] = time;
                str[1] = excelModel.getNickName();
                str[2] = excelModel.getPhone();
                str[3] = excelModel.getRealityName();
                String vip = excelModel.getVip();
                if (!"0".equals(vip)) {
                    str[4] = "是";
                }
                str[4] = "否";
                str[5] = excelModel.getResearchViews();
                str[6] = excelModel.getResearchShareViews();
                str[7] = excelModel.getAskViews();
                str[8] = excelModel.getAskShareViews();
                str[9] = excelModel.getProductViews();
                str[10] = excelModel.getIntegralShareViews();
                excelModels.add(str);
            }
        }
        String name = System.currentTimeMillis() + "_njk.xls";

        for (int j = 0; j < 2; j++) {
            if (j == 0) {
                String[] str1 = {"", "分享运营数据", "", "", "", "", "", "", "", "", ""};
                string.add(str1);
            } else {
                String[] str1 = {"", "昵称", "手机号", "姓名", "vip", "发帖", "分享帖子", "提问", "分享社区提问", "分享积分商品", "分享商品详情页"};
                string.add(str1);
            }
        }
        ExcelUtil.createExcelMerge_complexdo(name, string, excelModels, response);
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 帖子，商品，积分商品，对应的分享列表
     *
     * @param communityId
     * @param communityType 5 帖子 ，11 商品 ，12 积分商品
     * @return
     * @throws Exception
     */
    public ResponseResult researchShareList(String communityId, String communityType, Integer pageNum, Integer pageSize) throws Exception {
        PageInfo pageInfo = null;
        //查询帖子对应的分享信息
        ResearchEntity researchEntity = researchManageMapper.selectByPrimaryKey(communityId);
        //分页
        if (researchEntity != null) {
            PageHelper.startPage(pageNum, pageSize);
            List<ResearchShareListModel> researchShareListModels = countCommunityManageMapper.selectShareList(communityId, communityType);
            pageInfo = new PageInfo<>(researchShareListModels);
        }
        //查询商品对应的分享信息
        ProductEntity productEntity = productMapper.selectByPrimaryKey(communityId);
        if (productEntity != null) {
            PageHelper.startPage(pageNum, pageSize);
            List<ResearchShareListModel> researchShareListModels = countCommunityManageMapper.selectShareList(communityId, communityType);
            pageInfo = new PageInfo<>(researchShareListModels);
        }
        //查询积分商品对应的分享信息
        IntegralEntity integralEntity = integralManagerMapper.selectByPrimaryKey(communityId);
        if (integralEntity != null) {
            PageHelper.startPage(pageNum, pageSize);
            List<ResearchShareListModel> researchShareListModels = countCommunityManageMapper.selectShareList(communityId, communityType);
            pageInfo = new PageInfo<>(researchShareListModels);
        }

        return new ResponseResult(ResponseMessage.OK, pageInfo);
    }

    /**
     * 社区广告轮播图
     *
     * @return
     */
    public ResponseResult researchBanner(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ResearchBannerEntity> researchBannerEntities = researchBannerManageMapper.selectAll();
        PageInfo pageInfo = new PageInfo<>(researchBannerEntities);
        return new ResponseResult(ResponseMessage.OK, pageInfo);
    }

    /**
     * 删除轮播图
     *
     * @param id
     * @return
     */
    public ResponseResult delBanner(String id) {
        int i = researchBannerManageMapper.deleteByPrimaryKey(id);
        if (i == 0) {
            return new ResponseResult(ResponseMessage.FAIL, "删除失败");
        }
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 添加轮播图
     *
     * @param bannerType    图片类型
     * @param imgUrl        社区版图
     * @param popImgUrl     弹窗图
     * @param bannerExplain 版图描述
     * @param bannerId      链接类型ID
     * @param url           链接url
     * @return
     */
    public ResponseResult addBanner(Integer bannerType, String imgUrl, String bannerName, String popImgUrl, String bannerExplain, String bannerId, String url, String sort) {
        ResearchBannerEntity researchBannerEntity = new ResearchBannerEntity();
        researchBannerEntity.setCreateTime(new Date());
        researchBannerEntity.setBannerExplain(bannerExplain);
        researchBannerEntity.setBannerType(bannerType);
        researchBannerEntity.setImgUrl(imgUrl);
        researchBannerEntity.setPopImgUrl(popImgUrl);
        researchBannerEntity.setResearchBannerId(bannerId);
        researchBannerEntity.setUrl(url);
        researchBannerEntity.setSort(sort);
        researchBannerEntity.setBannerName(bannerName);
        researchBannerManageMapper.insert(researchBannerEntity);
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 修改轮播图
     *
     * @param bannerType    图片类型
     * @param imgUrl        社区版图
     * @param popImgUrl     弹窗图
     * @param bannerExplain 版图描述
     * @param bannerId      链接类型ID
     * @param url           链接url
     * @return
     */
    public ResponseResult updateBanner(Integer id, Integer bannerType, String imgUrl, String bannerName, String popImgUrl, String bannerExplain, String bannerId, String url, String sort) {
        ResearchBannerEntity researchBannerEntity = new ResearchBannerEntity();
        researchBannerEntity.setId(id);
        if (!"".equals(url) && url != null) {
            researchBannerEntity.setUrl(url);
        }
        if (!"".equals(imgUrl) && imgUrl != null) {
            researchBannerEntity.setImgUrl(imgUrl);
        }
        if (!"".equals(popImgUrl) && popImgUrl != null) {
            researchBannerEntity.setPopImgUrl(popImgUrl);
        }
        if (!"".equals(popImgUrl) && popImgUrl != null) {
            researchBannerEntity.setPopImgUrl(popImgUrl);
        }
        if (!"".equals(bannerExplain) && bannerExplain != null) {
            researchBannerEntity.setBannerExplain(bannerExplain);
        }
        if (!"".equals(sort) && sort != null) {
            researchBannerEntity.setSort(sort);
        }
        if (!"".equals(bannerName) && bannerName != null) {
            researchBannerEntity.setBannerName(bannerName);
        }
        researchBannerEntity.setBannerType(bannerType);
        researchBannerEntity.setResearchBannerId(bannerId);
        researchBannerManageMapper.updateByPrimaryKeySelective(researchBannerEntity);
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 活动帖子列表
     *
     * @return
     * @throws Exception
     */
    public ResponseResult researchActiveList() throws Exception {
        Example example = new Example(ResearchEntity.class);
        example.createCriteria().andEqualTo("operatingStatus", 1);
        List<ResearchEntity> researchEntities = researchManageMapper.selectByExample(example);
        return new ResponseResult(ResponseMessage.OK, researchEntities);
    }

    /**
     * 帖子活动运营数据
     *
     * @param researchId
     * @param activeType
     * @return
     * @throws Exception
     */
    public ResponseResult researchActiveData(String researchId, List<Integer> activeType) throws Exception {
        //获取活动帖子的开始和结束时间
        ResearchEntity researchEntity = researchManageMapper.selectByPrimaryKey(researchId);
        Date date = DateUtil.parse(researchEntity.getRecoverDate(), "yyyy-MM-dd");
        String format = DateUtil.format(date, "yyyy-MM-dd");

        String format1 = DateUtil.format(researchEntity.getActiveEndTime(), "yyyy-MM-dd");
        Date date1 = DateUtil.parse(format1, "yyyy-MM-dd");
        List<HashMap<String, Long>> activeDay = researchManageMapper.findActiveDay(researchId, activeType, format, date1);
        List<ResearchActiveTypeModel> typeModelList = new ArrayList<>();
        for (HashMap<String, Long> stringLongHashMap : activeDay) {
            ResearchActiveTypeModel typeModel = new ResearchActiveTypeModel();
         //   typeModel.setDay(stringLongHashMap.get("day"));
        }




/*
        List<ResearchActiveTypeModel> typeModelList = new ArrayList<>();
        for (ResearchActiveModel researchActiveModel : activeDay) {
            ResearchActiveTypeModel typeModel = new ResearchActiveTypeModel();
            List list = new ArrayList();

            if (researchActiveModel.getDay().equals(researchActiveModel.getDay())){
                typeModel.setDay(researchActiveModel.getDay());
                list.add(researchActiveModel.getType());
                list.add(researchActiveModel.getNumber());
                typeModel.setTypes(list);
            }else {
                typeModel.setDay(researchActiveModel.getDay());
                list.add(researchActiveModel.getType());
                list.add(researchActiveModel.getNumber());
                typeModel.setTypes(list);
            }


            typeModelList.add(typeModel);
        }*/
        return new ResponseResult(ResponseMessage.OK,typeModelList);
    }

    /**
     * 活动帖子运营总数
     * @param researchId
     * @param activeType
     * @return
     * @throws Exception
     */
    public ResponseResult activeDateNumber(String researchId,List<Integer> activeType) throws Exception{
        //获取活动帖子的开始和结束时间
        ResearchEntity researchEntity = researchManageMapper.selectByPrimaryKey(researchId);
      //  List<ResearchActiveModel> activeDay = researchManageMapper.findActiveDay(researchId, activeType, researchEntity.getRecoverDate(), researchEntity.getActiveEndTime());

        //计算总数
    /*    for(int i=0;i<list.size();i++){
            Student student=list.get(i);
            if (!student.getStatus().equals(1)) {
                String store=student.getStore();
                Date date=student.getDate();

                for (int j = i+1; j < list.size(); j++) {
                    if (!list.get(j).getStatus().equals(1)) {
                        Student mergeStudent=list.get(j);
                        if (mergeStudent.getStore().equals(store) && DateUtils.isSameDay(date, mergeStudent.getDate())) {
                            student.setMoney(student.getMoney()+mergeStudent.getMoney());

                            mergeStudent.setStatus(1);
                        }
                    }
                }
            }
        }*/

       return new ResponseResult(ResponseMessage.OK);
    }
}

